<template>
  <view>
    <button @click="showPicker">选择地区</button>
    <picker mode="selector" :range="filteredProvinces" @change="onPickerChange" v-if="pickerVisible">
      <view class="picker">
        <input type="text" v-if="pickerVisible" v-model="searchQuery" placeholder="搜索地区" />
        {{ selectedProvince }}
      </view>
    </picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      provinces: ['安徽省', '北京市', '上海市', '重庆市', '福建省', '甘肃省'],
      selectedProvince: '请选择',
      searchQuery: '',
      pickerVisible: false,
      letters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
    };
  },
  computed: {
    sortedProvinces() {
      const allItems = this.provinces.concat(this.letters);
      return allItems.sort((a, b) => {
        const charA = a.match(/[A-Z]/) ? a.match(/[A-Z]/)[0] : a.charAt(0).toUpperCase();
        const charB = b.match(/[A-Z]/) ? b.match(/[A-Z]/)[0] : b.charAt(0).toUpperCase();
        return charA.localeCompare(charB);
      });
    },
    filteredProvinces() {
      if (this.searchQuery) {
        return this.provinces.filter(province =>
          province.toLowerCase().includes(this.searchQuery.toLowerCase())
        );
      }
      return this.provinces;
    }
  },
  methods: {
    showPicker() {
      this.selectedProvince = '请选择';
      this.searchQuery = '';
      this.pickerVisible = true;
    },
    onPickerChange(e) {
      if (e.detail.value === -1) {
        this.selectedProvince = '请选择';
      } else {
        this.selectedProvince = this.filteredProvinces[e.detail.value];
      }
    }
  }
}
</script>

<style>
.picker {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>